package com.txw.travel.controller.backstage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.txw.travel.bean.RoleWithStatus;
import com.txw.travel.pojo.Admin;
import com.txw.travel.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/backstage/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/all")
    @PreAuthorize("hasAnyAuthority('/admin/all')")
    public ModelAndView All(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "3") int size) {
        ModelAndView modelAndView = new ModelAndView();
        Page<Admin> adminList = adminService.getAdminList(page, size);
        modelAndView.addObject("adminList", adminList);
        modelAndView.setViewName("/backstage/admin_all");
        return modelAndView;
    }

    @RequestMapping("/add")
    public String Add(Admin admin) {
        adminService.insert(admin);
        return "redirect:/backstage/admin/all";
    }

    @RequestMapping("/edit")
    public ModelAndView Edit(int id) {
        Admin admin = adminService.getAdminById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("admin", admin);
        modelAndView.setViewName("/backstage/admin_edit");
        return modelAndView;
    }

    @RequestMapping("/update")
    public String Update(Admin admin) {
        adminService.update(admin);
        return "redirect:/backstage/admin/all";
    }

    @RequestMapping("/detail")
    public ModelAndView Detail(int id) {
        Admin admin = adminService.getAdminDetail(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("admin", admin);
        modelAndView.setViewName("/backstage/admin_detail");
        return modelAndView;
    }

    @RequestMapping("/setRole")
    public ModelAndView setRole(int id) {
        List<RoleWithStatus> roleList = adminService.getRoleWithStatusList(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("aid", id);
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("/backstage/admin_role");
        return modelAndView;
    }

    @RequestMapping("/updateRole")
    public String updateRole(Integer aid, Integer[] rids) {
        adminService.updateAdminRole(aid, rids);
        return "redirect:/backstage/admin/all";
    }

    @RequestMapping("/updateStatus")
    public String updateStatus(Integer id){
        adminService.updateAdminStatus(id);
        return "redirect:/backstage/admin/all";
    }
}
